/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lambkit.module.cms.service;

import com.lambkit.core.Lambkit;
import com.lambkit.db.DbPool;
import com.lambkit.db.AbstractDaoService;
import com.lambkit.db.IRowDao;
import com.lambkit.module.cms.CmsConfig;
import com.lambkit.module.cms.row.CmsCategory;
import com.lambkit.util.Printer;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date ${date}
 * @version 1.0
 * @since 1.0
 */

public class CmsCategoryService extends AbstractDaoService<CmsCategory> {
	public static CmsCategoryService of() {
		return Lambkit.get(CmsCategoryService.class);
	}

	public IRowDao<CmsCategory> dao() {
		String dbPoolName = Lambkit.config(CmsConfig.class).getDbPoolName();
		return DbPool.use(dbPoolName).dao(CmsCategory.class);
	}

	public IRowDao<CmsCategory> dao(String dbPoolName) {
		return DbPool.use(dbPoolName).dao(CmsCategory.class);
	}

	@Override
	public boolean save(CmsCategory record) {
		boolean flag = super.save(record);
		this.update(record);
		return flag;
	}

	@Override
	public boolean update(CmsCategory record) {
		Long pid = record.getPid();
		if(pid==null || pid.equals(0L)) {
			record.setPid(0L);
			record.setLevel(0);
			record.setPath("0-"+record.getCategoryId());
		} else {
			CmsCategory c = findById(record.getPid());
			if(c!=null) {
				record.setLevel(c.getLevel()+1);
				record.setPath(c.getPath() + "-" + record.getCategoryId());
			}
		}
		Printer.print(this, "db", "update cms_category：{}, dao is {}", record.getCategoryId(), dao().getClass().getName());
		return super.update(record);
	}
}
